//
//  HPDateTimeListView.m
//  V-POS
//
//  Created by handpay on 13-3-12.
//  Copyright (c) 2013年 handpay. All rights reserved.
//

#import "HPDateTimeListView.h"
#import "DefineUtil.h"
#import "Utility.h"
#import "CategoryUtil.h"
#import "HPUIEngine.h"

@interface HPDateTimeListView()

@property(nonatomic, retain) UIPickerView* datePickerView;

@property(nonatomic, retain) NSString *realValue;

@property(nonatomic, retain) UIView *dateTimeCharView;

@end

@implementation HPDateTimeListView
@synthesize datePickerView;

#define HORIZONTALPADDING 10
#define VERTICALPADDING 6
#define WIDTH_BUTTON 73
#define HEIGHT_BUTTON 44

- (UIBarButtonItem*) initcustomBarButton:(NSString*)imageName title:(NSString*)title selector:(SEL)sel
{
    UIImage* tempImage = [UIImage imageNamed:imageName];
    UIButton* tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tempButton setExclusiveTouch:YES];
    [tempButton setBackgroundImage:tempImage forState:UIControlStateNormal];
    [tempButton setTitle:title forState:UIControlStateNormal];
    [tempButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    tempButton.frame = CGRectMake(0, 0, [tempImage realSize].width, [tempImage realSize].height);
    [tempButton addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* barButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];
    return [barButton autorelease];
}

- (void) setDefaultDate:(UIPickerView*)pickerView{
    NSDate* nowDate = [NSDate date];
    
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents* comps = [calendar components:unitFlags fromDate:nowDate];
    
    switch (self.mode) {
        case HPDateTimeListViewModeDate:
            [pickerView selectRow:[pickerView numberOfRowsInComponent:0] - 1 inComponent:0 animated:NO];
            [pickerView selectRow:comps.month - 1 inComponent:1 animated:NO];
            [pickerView selectRow:comps.day - 1 inComponent:2 animated:NO];
            [pickerView reloadComponent:0];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            break;
        case HPDateTimeListViewModeTime:
            [pickerView selectRow:comps.hour - 1 inComponent:0 animated:NO];
            [pickerView selectRow:comps.minute - 1 inComponent:1 animated:NO];
            [pickerView selectRow:comps.second - 1 inComponent:2 animated:NO];
            [pickerView reloadComponent:0];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            break;
        case HPDateTimeListViewModeDateMonth:
            [pickerView selectRow:[pickerView numberOfRowsInComponent:0] - 1 inComponent:0 animated:NO];
            [pickerView selectRow:comps.month - 1 inComponent:1 animated:NO];
            [pickerView reloadComponent:0];
            [pickerView reloadComponent:1];
            break;
        case HPDateTimeListViewModeDateTime:
            [pickerView selectRow:[pickerView numberOfRowsInComponent:0] - 1 inComponent:0 animated:NO];
            [pickerView selectRow:comps.month - 1 inComponent:1 animated:NO];
            [pickerView selectRow:comps.day - 1 inComponent:2 animated:NO];
            [pickerView selectRow:comps.hour - 1 inComponent:3 animated:NO];
            [pickerView selectRow:comps.minute - 1 inComponent:4 animated:NO];
            [pickerView selectRow:comps.second - 1 inComponent:5 animated:NO];
            [pickerView reloadComponent:0];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView reloadComponent:3];
            [pickerView reloadComponent:4];
            [pickerView reloadComponent:5];
            break;
        default:
            break;
    }
    
}

- (void) dropClick:(UIButton*)button
{
    UIControl * control = [Utility currentResponseView:[HPUIENG getCurrentScreen].view];
    if ([control isFirstResponder]) {
        [control resignFirstResponder];
    }
    
    bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    bgView.backgroundColor = RGBACOLOR(0, 0, 0, 0.6);
//    bgView.alpha = 0.6;
    
    actionView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 216, ScreenWidth, ScreenHeight)];
    actionView.backgroundColor = [UIColor clearColor];
   
    if (self.datePickerView == nil) {
        UIPickerView* pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT_BUTTON, HPUIENG.scrWidth, 216)];
        pickerView.delegate = self;
        pickerView.backgroundColor = [UIColor whiteColor];
        pickerView.dataSource = self;
        pickerView.showsSelectionIndicator = YES;
        
        [self setDefaultDate:pickerView];
        
        self.datePickerView = pickerView;
        [pickerView release];
    }
    
    [actionView addSubview:self.datePickerView];
    
    if (self.mode == HPDateTimeListViewModeDateTime) {
        UIView *temp = [[UIView alloc] initWithFrame:(CGRect){45, 60, 250, 21}];
        [temp setUserInteractionEnabled:NO];
        [temp setBackgroundColor:[UIColor clearColor]];
        self.dateTimeCharView = temp;
        [temp release];
        
        [actionView addSubview:self.dateTimeCharView];
        
        [self generateDateTimeChar:(CGRect){0, 0, 21, 21} ch:@"年"];
        [self generateDateTimeChar:(CGRect){58, 0, 21, 21} ch:@"月"];
        [self generateDateTimeChar:(CGRect){100, 0, 21, 21} ch:@"日"];
        [self generateDateTimeChar:(CGRect){143, 0, 21, 21} ch:@"时"];
        [self generateDateTimeChar:(CGRect){184, 0, 21, 21} ch:@"分"];
        [self generateDateTimeChar:(CGRect){226, 0, 21, 21} ch:@"秒"];
    }
    
    UIToolbar* accessoryBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, HPUIENG.scrWidth, HEIGHT_BUTTON)];
    [accessoryBar setBarStyle:UIBarStyleBlack];
    
    NSMutableArray* buttons = [[NSMutableArray alloc] init];
    UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    [buttons addObject:[self initcustomBarButton:@"button_cancel.png" title:@"取消" selector:@selector(cancelClick:)]];
    [buttons addObject:flexibleSpace];
    // 将确认按钮背景改成黑色了
    [buttons addObject:[self initcustomBarButton:@"button_ok.png" title:@"完成" selector:@selector(confirmClick:)]];
    
    [flexibleSpace release];
    
    [accessoryBar setItems:buttons animated:YES];
    [buttons release];
    [actionView addSubview:accessoryBar];
    [accessoryBar release];
    
    [bgView addSubview:actionView];
    
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];

//    [actionSheet showFromRect:CGRectMake(0, 0, HPUIENG.scrWidth, HPUIENG.scrHeight) inView:[UIApplication sharedApplication].keyWindow animated:YES];
//    [actionSheet release];
}

- (void) confirmClick:(UIButton*)button
{
    NSString* showText;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDate *date;
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            showText = [NSString stringWithFormat:@"%@-%02d-%02d", [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1)];
            [formatter setDateFormat:@"yyyy-M-d"];
            date = [formatter dateFromString:showText];
            [formatter setDateFormat:@"yyyyMMdd"];
            self.realValue = [formatter stringFromDate:date];
            break;
        }
        case HPDateTimeListViewModeTime: {
            showText = [NSString stringWithFormat:@"%d:%d:%d", ([self.datePickerView selectedRowInComponent:0] + 1), ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1)];
            [formatter setDateFormat:@"H:m:s"];
            date = [formatter dateFromString:showText];
            [formatter setDateFormat:@"HHmmss"];
            self.realValue = [formatter stringFromDate:date];
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            showText = [NSString stringWithFormat:@"%@年%d月", [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1)];
            [formatter setDateFormat:@"yyyy年M月"];
            date = [formatter dateFromString:showText];
            [formatter setDateFormat:@"yyyyMM"];
            self.realValue = [formatter stringFromDate:date];
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            showText = [NSString stringWithFormat:@"%@年%d月%d日 %d:%d:%d", [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1), ([self.datePickerView selectedRowInComponent:3] + 1), ([self.datePickerView selectedRowInComponent:4] + 1), ([self.datePickerView selectedRowInComponent:5] + 1)];
            [formatter setDateFormat:@"yyyy年M月d日 H:m:s"];
            date = [formatter dateFromString:showText];
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            self.realValue = [formatter stringFromDate:date];
            break;
        }
    }
    
    [formatter release];
    
    contentTextField.text = showText;
    
//    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    [bgView removeFromSuperview];
    bgView = nil;
}

- (NSString *) formatSelectDateTime:(NSString *)format
{
    NSString *ret;
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            ret = [NSString stringWithFormat:format, [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1)];
            break;
        }
        case HPDateTimeListViewModeTime: {
            ret = [NSString stringWithFormat:format, ([self.datePickerView selectedRowInComponent:0] + 1), ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1)];
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            ret = [NSString stringWithFormat:format, [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1)];
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            ret = [NSString stringWithFormat:format, [[self yearsSince1970] objectAtIndex:[self.datePickerView selectedRowInComponent:0]], ([self.datePickerView selectedRowInComponent:1] + 1), ([self.datePickerView selectedRowInComponent:2] + 1), ([self.datePickerView selectedRowInComponent:3] + 1), ([self.datePickerView selectedRowInComponent:4] + 1), ([self.datePickerView selectedRowInComponent:5] + 1)];
            break;
        }
    }
    return ret;
}

- (void) cancelClick:(UIButton*)button
{
    [bgView removeFromSuperview];
    bgView = nil;
//    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void) initializeWithFrame:(CGRect)frame
{
    [self setBackgroundColor:[UIColor clearColor]];
    
    UIImage *inputBgImage = [[UIImage imageNamed:@"selecte_bg.png"] stretchableImageWithLeftCapWidth:12. topCapHeight:.0];
    UIImage *dropImage = [UIImage imageNamed:@"down_tag.png"];
    
    CGFloat imageRightEdge = (frame.size.width - inputBgImage.size.width - HORIZONTALPADDING * 2);
    
    dropDownButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    
    
    [dropDownButton setBackgroundImage:inputBgImage forState:UIControlStateNormal];
    [dropDownButton setImage:dropImage forState:UIControlStateNormal];
    [dropDownButton setImageEdgeInsets:UIEdgeInsetsMake(0, imageRightEdge, 0, 0)];
    [dropDownButton addTarget:self action:@selector(dropClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:dropDownButton];
    
//    contentTextField = [[UITextField alloc] initWithFrame:frame];
    contentTextField = [[UITextField alloc] initWithFrame:CGRectMake(HORIZONTALPADDING, 0, imageRightEdge - HORIZONTALPADDING, frame.size.height)];
    contentTextField.userInteractionEnabled = NO;
    contentTextField.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    contentTextField.font = [UIFont systemFontOfSize:16];
    contentTextField.textColor = kGreenColor;
    if (self.label) {
        contentTextField.text = self.label;
    }else{
        contentTextField.text = @"测试日期";
    }
    int h = contentTextField.frame.size.height;
    int w = contentTextField.frame.size.width;
    [contentTextField sizeToFit];
    CGRect textFrame = contentTextField.frame;
    textFrame.origin.y = (h - textFrame.size.height) / 2;
    textFrame.size.width = w;
    contentTextField.frame = textFrame;

    [self addSubview:contentTextField];
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeWithFrame:frame];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame label:(NSString *)label_ mode:(HPDateTimeListViewMode)mode_
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initializeWithFrame:frame];
        self.label = label_;
        self.mode = mode_;
    }
    return self;
}

- (void) awakeFromNib
{
    self.mode = HPDateTimeListViewModeDateTime;
    [self initializeWithFrame:self.frame];
}

- (void) setMode:(HPDateTimeListViewMode)mode_
{
    _mode = mode_;
    
    self.datePickerView = nil;
    self.dateTimeCharView = nil;
}

- (void) setLabel:(NSString *)label_
{
    if (label_ != _label) {
        [_label release];
        _label = [label_ retain];
        contentTextField.text = _label;
    }
}

- (NSString *) value
{
    if (!self.realValue) {

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSDate *date;
        switch (self.mode) {
            case HPDateTimeListViewModeDate: {
                [formatter setDateFormat:@"yyyy-MM-dd"];
                date = [formatter dateFromString:contentTextField.text];
                [formatter setDateFormat:@"yyyyMMdd"];
                self.realValue = [formatter stringFromDate:date];
                break;
            }
            case HPDateTimeListViewModeTime: {
                break;
            }
            case HPDateTimeListViewModeDateMonth: {
                break;
            }
            case HPDateTimeListViewModeDateTime: {
                break;
            }
        }
        
        [formatter release];
    }
    return self.realValue;
}

- (void) dealloc
{
    self.datePickerView = nil;
    [bgView release];
    [actionView release];
    [dropDownButton release];
    [contentTextField release];
    self.dateTimeCharView = nil;
    
    [super dealloc];
}

#pragma mark picker view datasource

- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            return 3;
            break;
        }
        case HPDateTimeListViewModeTime: {
            return 3;
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            return 2;
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            return 6;
            break;
        }
    }
    return 0;
}

- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            switch (component) {
                case 0: {
                    return [self yearsSince1970].count;
                    break;
                }
                case 1: {
                    return 12;
                    break;
                }
                case 2: {
                    return [self daysInYear:[[[self yearsSince1970] objectAtIndex:[pickerView selectedRowInComponent:0]] intValue] month:([pickerView selectedRowInComponent:1] + 1)];
                    break;
                }
            }
            break;
        }
        case HPDateTimeListViewModeTime: {
            switch (component) {
                case 0: {
                    return 24;
                    break;
                }
                case 1: {
                    return 60;
                    break;
                }
                case 2: {
                    return 60;
                    break;
                }
            }
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            switch (component) {
                case 0: {
                    return [self yearsSince1970].count;
                    break;
                }
                case 1: {
                    return 12;
                    break;
                }
            }
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            switch (component) {
                case 0: {
                    return [self yearsSince1970].count;
                    break;
                }
                case 1: {
                    return 12;
                    break;
                }
                case 2: {
                    return [self daysInYear:[[[self yearsSince1970] objectAtIndex:[pickerView selectedRowInComponent:0]] intValue] month:([pickerView selectedRowInComponent:1] + 1)];
                    break;
                }
                case 3: {
                    return 24;
                    break;
                }
                case 4: {
                    return 60;
                    break;
                }
                case 5: {
                    return 60;
                    break;
                }
            }
            break;
        }
    }
    
    return 0;
}

#pragma mark - picker view delegate

#define kDateTimeYearWidth  70
#define kDateTimeOtherWidth 40

#define kYearWidth  85
#define kOtherWidth 60

- (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    switch (self.mode) {
        case HPDateTimeListViewModeTime: {
            return kOtherWidth;
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            if (component == 0) {
                // 年
                return kDateTimeYearWidth;
            }
            // 其他
            return kDateTimeOtherWidth;
            break;
        }
        default: {
            if (component == 0) {
                // 年
                return kYearWidth;
            }
            // 其他
            return kOtherWidth;
        }
    }
    return 0;
}

- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            if (component == 0) {
                return [NSString stringWithFormat:@"%d年", [[[self yearsSince1970] objectAtIndex:row] intValue]];
            } else if (component == 1) {
                return [NSString stringWithFormat:@"%02d月", (row + 1)];
            } else if (component == 2) {
                return [NSString stringWithFormat:@"%02d日", (row + 1)];
            }
            break;
        }
        case HPDateTimeListViewModeTime: {
            if (component == 0) {
                return [NSString stringWithFormat:@"%02d时", (row + 1)];
            } else if (component == 1) {
                return [NSString stringWithFormat:@"%02d分", (row + 1)];
            } else if (component == 2) {
                return [NSString stringWithFormat:@"%02d秒", (row + 1)];
            }
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            if (component == 0) {
                return [NSString stringWithFormat:@"%d年", [[[self yearsSince1970] objectAtIndex:row] intValue]];
            } else if (component == 1) {
                return [NSString stringWithFormat:@"%02d月", (row + 1)];
            }
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            if (component == 0) {
                return [NSString stringWithFormat:@"%d", [[[self yearsSince1970] objectAtIndex:row] intValue]];
            }
            return [NSString stringWithFormat:@"%02d", (row + 1)];
            break;
        }
    }
    return nil;
}

- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (self.mode) {
        case HPDateTimeListViewModeDate: {
            if(component == 1 || component == 0){
                [self.datePickerView reloadComponent:2];
            }
           break;
        }
        case HPDateTimeListViewModeTime: {
            break;
        }
        case HPDateTimeListViewModeDateMonth: {
            break;
        }
        case HPDateTimeListViewModeDateTime: {
            break;
        }
    }
}

#pragma mark - 私有方法

- (NSString *) formatTitle:(NSString *)title
{
    if (title.length == 1) {
        return [NSString stringWithFormat:@"0%@", title];
    }
    return title;
}

/**
 * 获取1970年至今的年数
 */
- (NSArray *) yearsSince1970
{
    NSMutableArray *ret = [NSMutableArray array];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy"];
    int currentYear = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    [dateFormatter release];
    for (int i = currentYear - 10; i <= currentYear; i ++) {
        [ret addObject:[NSNumber numberWithInt:i]];
    }
    return ret;
}

/**
 * 判断给定年是否为闰年
 */
- (BOOL) isLeapYear:(int)year
{
    NSString *yearString = [NSString stringWithFormat:@"%d", year];
    if ([yearString hasSuffix:@"00"]) {
        return year % 400 == 0;
    } else {
        return year % 4 == 0;
    }
    return NO;
}

/**
 * 根据年和月获取天数
 */
- (int) daysInYear:(int)year month:(int)month
{
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        return 31;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        return 30;
    }
    if ([self isLeapYear:year]) {
        // 闰年2月份29天
        return 29;
    }
    // 平年2月份28天
    return 28;
}

- (void) generateDateTimeChar:(CGRect)frame ch:(NSString *)ch
{
    UILabel *charLabel = [[UILabel alloc] initWithFrame:frame];
    [charLabel setBackgroundColor:[UIColor clearColor]];
    [charLabel setFont:[UIFont systemFontOfSize:18]];
    [charLabel setText:ch];
    [self.dateTimeCharView addSubview:charLabel];
    [charLabel release];
}

@end
